package dmsxl.tanxin;

/**
 * Author: Zhang Dongwei
 * Date: 2023/7/31 20:32
 */
public class tx12_135 {

    public static void main(String[] args) {
//        int[] ratings = {1, 0, 2};
//        int[] ratings = {1, 2, 2};
        int[] ratings = {1, 2, 87, 87, 87, 2, 1};
        System.out.println(candy(ratings));
    }

//    自己写的有问题，视频中给出了这个方法错误的原因
    public static int candy1(int[] ratings) {
        int sum = 0;
        int l = 1, c = 1;
        sum += l;
        if (ratings.length == 1) return 1;
        if (ratings.length == 2)
            if (ratings[0] != ratings[1]) return 3;
            else return 2;
        for (int i = 1; i < ratings.length; i++) {
            if (ratings[i - 1] < ratings[i]) {
                c = l + 1;
                sum += c;
                l = c;
            } else if (ratings[i - 1] == ratings[i]) {
                sum += 1;
                l = 1;
            } else {
                if (l == 1) {
                    sum += 1;
                }
                sum += 1;
                l = c;
            }
            System.out.println(i);
            System.out.println(sum);
        }
        return sum;
    }

//    答案
    public static int candy(int[] ratings) {
        int[] candies = new int[ratings.length];
        int sum = 0;
        for (int i = 0; i < candies.length; i++){
            candies[i] = 1;
        }
        for (int i = 1; i < ratings.length; i++){
            if (ratings[i] > ratings[i - 1]){
                candies[i] = candies[i - 1] + 1;
            }
        }
        for (int i = ratings.length - 2; i >= 0; i--){
            if (ratings[i] > ratings[i + 1]){
                candies[i] = Math.max(candies[i + 1] + 1, candies[i]);
            }
        }
        for (int i = 0; i < candies.length; i++){
            sum += candies[i];
        }
        return sum;
    }
}
